package com.kun.demo04_synchronize.probelm;


import org.junit.Test;

//买火车票问题，线程不安全
public class NotSafeCase1_buyTickets {

    private int tickets = 10;

    class Ticket implements Runnable{
        @Override
        public void run() {
            while (true){
                if (tickets <= 0){
                    return;
                }

                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

                System.out.println(Thread.currentThread().getName() + " 正在买第 " + tickets-- + " 张票...");
            }

        }
    }



    @Test
    public void test() throws InterruptedException {
        System.out.println("开始买票...");
        Ticket ticket = new Ticket();
        new Thread(ticket, "A").start();
        new Thread(ticket, "B").start();
        new Thread(ticket, "C").start();
        Thread.sleep(2000); // 延迟主线程退出
    }
}


